import os
from urllib import request
import time
import requests
import json

open('herolist.json', 'wt', encoding='utf-8').write(requests.get(url='https://pvp.qq.com/web201605/js/herolist.json')
       .content.decode('utf-8')) if not os.path.exists('herolist.json') else 111
json_base_url = 'https://pvp.qq.com/zlkdatasys/yuzhouzhan/herovoice/'
herolist = open('herolist.json', 'r', encoding='utf-8').read()
herolist = eval(herolist)
herolist = {
    str(i['ename']): (i['cname'], i['title'])
    for i in herolist
}
herolist.pop('509') if '509' in herolist.keys() else 111  # 盾山没语音

os.mkdir('data') if not os.path.exists('data') else 111
os.mkdir('out') if not os.path.exists('out') else 111

for code, v in herolist.items():
    url = json_base_url + code + '.json'

    if os.path.exists('data/' + code + '.json'):
        print("%s-%s-%s 信息已存在" % (code, v[1], v[0]))
        pass
    else:
        url = json_base_url + code + '.json'
        req = request.Request(url=url, method='get')
        res = request.urlopen(req)
        jsonstr = res.read().replace(b'\/', b'/').decode('unicode_escape')
        if code == '109':
            # 妲己 青丘皮肤台词处理
            jsonstr = jsonstr.replace(r'"喜欢"', r'“喜欢”')
            jsonstr = jsonstr.replace(r'"最喜欢"', r'“最喜欢”')
            pass
        open('data/' + code + '.json', 'w', encoding='utf-8').write(jsonstr)
        print("%s-%s-%s 信息已完成下载" % (code, v[1], v[0]))
        time.sleep(0.1)

for code in herolist.keys():
    file = open('data/' + code + '.json', 'r', encoding='utf-8')
    jsonstr = file.read()
    voice_info = eval(jsonstr)
    voice_info = voice_info['dqpfyy_5403']
    if isinstance(voice_info, dict):
        voice_info = [voice_info]
    voice_info = {
        i['pfmczt_7754']: [
            (j['yywbzt_1517'], 'http:' + j['yywjzt_5304'])
            for j in i['yylbzt_9132']
        ]
        for i in voice_info
    }
    dirname = 'out/' + herolist[code][0]
    os.mkdir(dirname) if not os.path.exists(dirname) else 111
    for name, voice in voice_info.items():
        dirname = 'out/' + herolist[code][0] + '/' + name
        os.mkdir(dirname) if not os.path.exists(dirname) else 111
        for index, info in enumerate(voice, start=1):
            # dirname/index-content.[mp3/wav/...]
            filename = dirname + '/' + \
                str(index) + '-' + info[0] + info[1][-4:]
            if os.path.exists(filename):
                print("%s 已存在, 跳过" % filename)
                continue
            else:
                voice_response = requests.get(info[1]).content
                open(filename, 'wb').write(voice_response)
                print("%s 下载完成" % filename)
                time.sleep(0.5)
